import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_ywt/config/event_manager.dart';
import 'package:flutter_ywt/config/theme/size.dart';

///描述：带进度显示的 对话框
///author：gyy
class ProgressDialog extends StatefulWidget {
  //提示文字
  String title;
  //提示进度
  double value;
  //是否可点击返回按钮 关闭对话框: 默认false
  bool canBack = false;

  ProgressDialog(this.title, {this.value, this.canBack});
  @override
  _ProgressDialogState createState() => _ProgressDialogState();
}

class _ProgressDialogState extends State<ProgressDialog> {
  double value;
  String title;
  bool canBack;
  var subscription;
  @override
  void initState() {
    super.initState();
    this.value = widget.value;
    this.title = widget.title;
    this.canBack = widget.canBack;
    //监听进度事件(只能放在initState中，放在build中，存在bug)
    subscription = eventBus.on<ProgressEvent>().listen((event) => {
      setState(() {
        value = event.value;
      })
    });
  }
  @override
  Widget build(BuildContext context) {
    //文本显示
    String getValue() {
      if(value != null) {
        String text = (value * 100).toStringAsFixed(0);
        return title + text + "/100";
      }
      return title;
    }
    return WillPopScope (
      onWillPop: () {
        return Future.value(canBack);
      },
      child: Material(
        type: MaterialType.transparency,
        child: new Center(
          child: new ConstrainedBox(
            constraints: BoxConstraints(
                minHeight: size140,
                minWidth: size140,
                maxWidth: size160,
                maxHeight: size160
            ),

            child: new Container(
              decoration: ShapeDecoration(
                color: Color(0xffffffff),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(
                    Radius.circular(8.0),
                  ),
                ),
              ),
              child: new Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  new CircularProgressIndicator(
                    value: value,
                    backgroundColor: Theme.of(context).scaffoldBackgroundColor,
                  ),
                  new Padding(
                    padding: const EdgeInsets.only(
                      top: 20.0,
                    ),
                    child: new Text(getValue(), maxLines: 1,),
                  ),
                ],
              ),
            ),
          ),
        ),
      )
    );

  }

  @override
  void dispose() {
    super.dispose();
    if(subscription != null) {
      subscription.cancel();
      subscription = null;
    }
  }
}
